const db = require('../db/index')
const bcrypt = require('bcryptjs')

//获取用户信息的处理函数
exports.getUserinfo = (req, res) => {
    // res.send(req.user)
    const { id } = req.user

    const sql = `select * from ev_users where id=?`

    db.query(sql, [id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length == 0) return res.cc('获取用户数据失败！')
        console.log(results);
        res.send({
            status: 0,
            message: '获取用户信息成功！',
            //使用拓展运算符把results[0]解构出来，然后再重新赋值password为undefined，可以去除password属性
            data: {
                ...results[0],
                password: undefined
            }
        })
    })
}

//更新用户信息的处理函数
exports.updateUserInfo = (req, res) => {
    const { id, nickname, email } = req.body

    const sql = `update ev_users set nickname=?,email=? where id=?`

    db.query(sql, [nickname, email, id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('更新用户数据失败！')
        console.log(results);
        res.send({
            status: 0,
            message: '修改用户信息成功！',
        })
    })
}

//更新密码的处理函数
exports.updatepwd = (req, res) => {
    const { id } = req.user

    const sql = `select password from ev_users where id=?`

    db.query(sql, [id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length == 0) return res.cc('原密码错误！')
        console.log(results);
        const { password: hash } = results[0]
        const { oldPwd, newPwd } = req.body
        const isSame = bcrypt.compareSync(oldPwd, hash)
        if (!isSame) return res.cc('原密码错误！')

        const sql = `update ev_users set password=? where id=?`

        db.query(sql, [bcrypt.hashSync(newPwd), id], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('修改密码失败！')
            res.send({
                status: 0,
                message: '修改密码成功！',
            })
        })
    })
}

//更新头像的处理函数
exports.updateAvatar = (req, res) => {
    const sql = 'update ev_users set user_pic=? where id=?'

    db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('修改头像失败！')
        res.send({
            status: 0,
            message: '修改头像成功！',
        })
    })
}